package com.lyl.security.module.security.handler;

import com.lyl.security.common.result.ErrorCode;
import com.lyl.security.common.result.Result;
import com.lyl.security.common.utils.ServletUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author Mr.Luo
 * @date 2022-09-14 11:45
 * @desc 认证异常处理程序
 */
@Slf4j
@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException e) throws IOException, ServletException {
        log.error("认证异常", e);
        if (e instanceof InsufficientAuthenticationException) {
            ServletUtils.write(response, Result.build(ErrorCode.UNAUTHORIZED).setMsg("身份认证信息不足"));
        } else {
            ServletUtils.write(response, Result.build(ErrorCode.UNAUTHORIZED, e.getMessage()));
        }
    }
}
